/**
 * Copyright @ 2000 ysten Co. Ltd. 
 * All right reserved.     
 * @author: wangmin
 * date: 2016-05-15     
 */
package com.task.controller;

import com.google.common.collect.Lists;
import com.task.bean.Constants;
import com.task.bean.EnumConstants;
import com.task.bean.EnumConstants.ParentTaskStatus;
import com.task.bean.ParentTaskBean;
import com.task.entity.ChildTask;
import com.task.entity.ParentTask;
import com.task.entity.Store;
import com.task.service.*;
import com.task.utils.*;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 任务发布控制器
 */
@Controller
@RequestMapping("/web")
public class ParentTaskController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ParentTaskController.class);

    private static DecimalFormat DF = new DecimalFormat("##.00");

	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		/**
		 * 防止XSS攻击
		 */
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));

		/**
		 * 自动转换日期类型的字段格
		 */
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}

	@Autowired
	IParentTaskService parentTaskService;

	@Autowired
	IChildTaskService childTaskService;

	@Autowired
	ICheckLogService checkLogService;

	@Autowired
	IFinishTasksService finishTaskService;

	@Autowired
	ISystemService systemService;

	@Autowired
	IStoreService storeService;

	@RequestMapping(value = "/taskPublish.html")
	public String toParentTaskList() {
		return "/task/parent_task_list";
	}

	@RequestMapping(value = "/mainTaskDetail.html")
	public String mainTaskDetail(ModelMap model, @RequestParam(value = "id") Long id) {
		ParentTask pt = parentTaskService.findById(id);
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("EQ_parentTaskId", id);
		List<ChildTask> childTaskList = childTaskService.findByCondition(searchParams);
		List<TaskDomain> taskList = new ArrayList<TaskDomain>();

		for (ChildTask child : childTaskList) {
			TaskDomain domain = new TaskDomain();
			domain.setId(child.getId().toString());
			if (child.getStore() != null) {
				domain.setStoreAddress(child.getStore().getStoreAddress());
			}
			domain.setStoreCode(child.getStoreCode());
			domain.setTaskName(pt.getTaskName());
			domain.setEndDate(pt.getEndTime());
			domain.setStartDate(pt.getStartTime());
			taskList.add(domain);
		}
		if (StringUtils.isNotBlank(pt.getTaskGuidancePictures())) {
			String pics = pt.getTaskGuidancePictures();
			String[] picArr = StringUtils.split(pics, ",");
			List<String> imagesList = Lists.newArrayList();
			for (String pic : picArr) {
				imagesList.add(pic);
			}
			pt.setImagesList(imagesList);
		}
		if (pt.getTaskType() != null) {
			pt.setTaskTypaName(pt.getTaskType().getMsg());
		}
		model.addAttribute("data", JsonUtils.toJson(taskList));
		model.addAttribute("pt", pt);
		return "/task/mainTaskDetail";
	}

	@RequestMapping(value = "/mainTaskManage.html")
	public String mainTaskManage(ModelMap model, @RequestParam(value = "id") Long id) {
		ParentTask pt = parentTaskService.findById(id);
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("EQ_parentTaskId", id);
		List<ChildTask> childTaskList = childTaskService.findByCondition(searchParams);
		List<TaskDomain> taskList = new ArrayList<TaskDomain>();

		for (ChildTask child : childTaskList) {
			TaskDomain domain = new TaskDomain();
			domain.setId(child.getId().toString());
			if (child.getStore() != null) {
				domain.setStoreAddress(child.getStore().getStoreAddress());
			}
			domain.setCode(child.getCode());
			domain.setStoreCode(child.getStoreCode());
			domain.setTaskName(pt.getTaskName());
			domain.setEndDate(pt.getEndTime());
			domain.setStartDate(pt.getStartTime());
			taskList.add(domain);
		}
		if (StringUtils.isNotBlank(pt.getTaskGuidancePictures())) {
			String pics = pt.getTaskGuidancePictures();
			pics = pics.replace("\\", "/");
			pt.setTaskGuidancePictures(pics);
			String[] picArr = StringUtils.split(pics, ",");
			List<String> imagesList = Lists.newArrayList();
			for (String pic : picArr) {
				imagesList.add(pic);
			}
			pt.setImagesList(imagesList);
		}
		if (pt.getTaskType() != null) {
			pt.setTaskTypaName(pt.getTaskType().getMsg());
		}
		model.addAttribute("data", JsonUtils.toJson(taskList));
		model.addAttribute("task", pt);
		return "/task/mainTaskManage";
	}

	@RequestMapping(value = "/mainTaskProgress.html")
	public String mainTaskProgress(ModelMap model, @RequestParam(value = "id") Long id) {
		try {
			if (id != null) {
				// 查询主任务
				ParentTask pt = parentTaskService.findById(id);

				if (StringUtils.isNotBlank(pt.getTaskGuidancePictures())) {
					String pics = pt.getTaskGuidancePictures();
					String[] picArr = StringUtils.split(pics, ",");
					List<String> imagesList = Lists.newArrayList();
					for (String pic : picArr) {
						imagesList.add(pic);
					}
					pt.setImagesList(imagesList);
				}
				if (pt.getTaskType() != null) {
					pt.setTaskTypaName(pt.getTaskType().getMsg());
				}

				// 查询主任务下所有子任务
				List<ChildTask> childTaskList = new ArrayList<ChildTask>();
				Map<String, Object> searchParams = new HashMap<String, Object>();
				searchParams.put("EQ_parentTaskId", id);
				childTaskList = childTaskService.findByCondition(searchParams);

				long childTaskNum = 0;
				// 获取子任务的个数
				if (childTaskList.isEmpty()) {
					pt.setChildNumber("0");
				} else {
					pt.setChildNumber(String.valueOf(childTaskList.size()));
					childTaskNum = childTaskList.size();
				}
				pt.setChildTaskList(childTaskList);

				// 主任务 总天数
				long allDays = DateTimeUtils.getBetweenDays(pt.getStartTime(), pt.getEndTime());
				// 获取当前日期
				String nowDate = DateTimeUtils.formatDateToStringWithOnlyDate(new Date());
				// 计算今天据任务发出的时间
				long alreadyDays = DateTimeUtils.getBetweenDays(pt.getStartTime(), nowDate);
				model.put("allDays", allDays+1);
				if (alreadyDays > allDays) {
					alreadyDays = allDays;
				}
				model.put("alreadyDays", alreadyDays);

				// 已完成的数量[已提交+审核通过+审核未通过]
				Integer finishTaskNum = 0;
				// 审核通过数量
				Integer checkPassNum = 0;
				// 审核未通过数量
				Integer checkNoPassNum = 0;
				// 审核的数量 =[审核通过+审核不通过]
				Integer checkNum = 0;
				// 已接单数目
				Integer pickUpNum = 0;
				// 待审核
				Integer waitCheck = 0;
				for (ChildTask child : childTaskList) {
					if (null != child.getUserId()) {
						pickUpNum++;
					}
					switch (child.getStatus()) {
					case SAVE:
						break;
					case PUBLISH:
						break;
					case DOING:
						break;
					case SUBMIT:
						// finishTaskNum++;
						waitCheck++;
						break;
					case PASS:
						finishTaskNum++;
						checkNum++;
						checkPassNum++;
						break;
					case NOPASS:
						//finishTaskNum++;
						checkNum++;
						checkNoPassNum++;
						break;
					case CLOSE:
						break;

					default:
						break;
					}
				}
				// 待审核
				model.addAttribute("waitCheck", waitCheck);
				// 已接单
				model.put("pickUpNum", pickUpNum);
				// 子任务数量
				model.put("childTaskNum", childTaskNum);
				// 已完成的子任务数量
				model.put("finishTaskNum", finishTaskNum);

				model.put("finishTaskNumRate", finishTaskNum + "/" + childTaskNum);
				model.put("waitCheckRate", waitCheck + '/' + childTaskNum);
				model.put("pickUpNumRate", pickUpNum + '/' + childTaskNum);

				// 总赏金
				float allReward = 0;
				// 已发出的赏金 [审核通过的子任务 * 赏金]
				float alreadyReward = 0;
				if (pt.getReward() != null) {
					allReward = childTaskNum * pt.getReward();
					alreadyReward = checkPassNum * pt.getReward();
				}

				model.put("allReward", allReward);
				model.put("alreadyReward", alreadyReward);

				// 已审核的数量
				model.put("checkNum", checkNum);
				// 审核未通过的数量
				model.put("checkNoPassNum", checkNoPassNum);
				// 审核通过的数量
				model.put("checkPassNum", checkPassNum);
				model.put("parentTask", pt);
				model.put("status", pt.getStatus().getMsg());
				if (childTaskNum == 0) {
					model.put("finishTaskNumPercent", 0);
				} else {
                    model.put("finishTaskNumPercent", Double.parseDouble(DF.format((float)finishTaskNum/childTaskNum * 100)));
				}
				if (allReward == 0) {
					model.put("alreadyRewardPercent", 0);
				} else {
                    model.put("alreadyRewardPercent", Double.parseDouble(DF.format(alreadyReward/allReward * 100)));
				}
			}
		} catch (Exception e) {
			LOGGER.error("  getParentTaskInfo by id error : {}", e);
		}
		return "/task/mainTaskProgress";
	}

	@RequestMapping(value = "/taskList.html")
	public String toTaskList() {
		return "/task/task_list";
	}

	/**
	 * <查询所有子任务列表>
	 *
	 * @param offset
	 * @param limit
	 * @param request
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@ResponseBody
	@RequestMapping(value = "/findChildTaskList.json")
	public JSONObject findChildTaskList(@RequestParam(value = "parentTaskId") Long parentTaskId,
			@RequestParam(value = "offset", defaultValue = Constants.DEFAULT_PAGE) int offset,
			@RequestParam(value = "limit", defaultValue = Constants.DEFAULT_ROWS) int limit, ServletRequest request) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(Constants.ROWS, new ArrayList<ParentTaskBean>());
		jsonObject.put(Constants.TOTAL, 0);
		try {
			int pageNum = offset / limit + 1;
			Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, Constants.SEARCH_PREFIX);
			searchParams.put("EQ_parentTaskId", parentTaskId);
			ParentTask pt = parentTaskService.findById(parentTaskId);
			Page<ChildTask> page = childTaskService.findTaskList(searchParams, pageNum, limit);
			if (page != null && CollectionUtils.isNotEmpty(page.getContent())) {
				List<TaskDomain> taskList = new ArrayList<TaskDomain>();

				for (ChildTask child : page.getContent()) {
					TaskDomain domain = new TaskDomain();
					domain.setId(child.getId().toString());
					domain.setStoreAddress(child.getStore().getStoreAddress());
					domain.setStoreCode(child.getStoreCode());
					domain.setStoreName(child.getStore().getStoreName());
					domain.setTaskName(pt.getTaskName());
					domain.setEndDate(pt.getEndTime());
					domain.setStartDate(pt.getStartTime());
					domain.setCode(child.getCode());
					if (child.getStatus() != null) {
						domain.setStatus(child.getStatus().getMsg());
					}
					taskList.add(domain);
				}
				jsonObject.put(Constants.ROWS, taskList);
				jsonObject.put(Constants.TOTAL, page.getTotalElements());
			}
		} catch (Exception e) {
			LOGGER.error("find parentTask page error:{}", e);
		}
		return jsonObject;
	}

	/**
	 * <查询所有主任务列表>
	 *
	 * @param offset
	 * @param limit
	 * @param request
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@ResponseBody
	@RequestMapping(value = "/findParentTaskPage.json")
	public JSONObject findParentTaskPage(
			@RequestParam(value = "offset", defaultValue = Constants.DEFAULT_PAGE) int offset,
			@RequestParam(value = "limit", defaultValue = Constants.DEFAULT_ROWS) int limit, ServletRequest request)throws Exception{
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(Constants.ROWS, new ArrayList<ParentTaskBean>());
		jsonObject.put(Constants.TOTAL, 0);
		try {
			int pageNum = offset / limit + 1;
			Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, Constants.SEARCH_PREFIX);
			System.out.println(searchParams);
			if (null != searchParams.get("EQ_status")
					&& StringUtils.isNotBlank(searchParams.get("EQ_status").toString())) {
				String status = searchParams.get("EQ_status").toString();
				EnumConstants.ParentTaskStatus parentTaskStatus = EnumConstants.ParentTaskStatus.valueOf(status);
				if (parentTaskStatus != null) {
					searchParams.put("EQ_status", parentTaskStatus);
				}
			}
			if (null != searchParams.get("LIKE_taskName")
					&& StringUtils.isNotBlank(searchParams.get("LIKE_taskName").toString())) {
				String LIKE_taskName = searchParams.get("LIKE_taskName").toString();
					searchParams.put("LIKE_taskName",  new String(LIKE_taskName.getBytes("ISO-8859-1"), "UTF-8"));
			}

			Page<ParentTask> page = parentTaskService.findParentTaskPage(searchParams, pageNum, limit);
			if (page != null && CollectionUtils.isNotEmpty(page.getContent())) {
				List<ParentTaskBean> parentTaskBeanList = Lists.newArrayList();
				Integer count;
				for (ParentTask parentTask : page.getContent()) {
					ParentTaskBean parentTaskBean = new ParentTaskBean();
					parentTaskBean.setId(parentTask.getId());
					parentTaskBean.setName(getHtmlTaskName(parentTask));
					count = childTaskService.getCountByParentTaskId(parentTask.getId());
					if (count != null) {
						parentTaskBean.setMun(count + "家");
					}
					parentTaskBean.setTime(parentTask.getStartTime() + "~" + parentTask.getEndTime());
					parentTaskBean.setStatus("<span class=\"ing\">" + parentTask.getStatus().getMsg() + "</span>");
					getChildInfo(parentTaskBean, parentTask.getId());
					parentTaskBeanList.add(parentTaskBean);
				}
				jsonObject.put(Constants.ROWS, parentTaskBeanList);
				jsonObject.put(Constants.TOTAL, page.getTotalElements());
			}
		} catch (Exception e) {
			LOGGER.error("find parentTask page error:{}", e);
		}
		return jsonObject;
	}

	private String getHtmlTaskName(ParentTask parentTask) {
		return "<div class=\"infoContainer\"><div class=\"circle\">" + parentTask.getTaskType().getMsg()
				+ "</div><div class=\"info\"><div class=\"name\">" + parentTask.getTaskName()
				+ "</div><div class=\"code\">" + parentTask.getCode() + "</div></div></div>";
	}

	/**
	 * <保存主任务>
	 *
	 * @param parentTask
	 * @param status
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value = "/saveParentTask.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject saveParentTask(ParentTask parentTask,
			@RequestParam(value = "storeCode", defaultValue = "") String storeCode,
			@RequestParam(value = "status", defaultValue = "SAVE") EnumConstants.ParentTaskStatus status) {
		JSONObject resultJson = new JSONObject();
		resultJson.put(Constants.RESULT, Constants.RESULT_FAIL);
		try {
			if (null == parentTask.getId()) {
				parentTask.setCreateTime(new Date());
			} else {
				parentTask.setUpdateTime(new Date());
			}
			parentTask.setStatus(status);
			parentTaskService.save(parentTask);
			if (status.equals(EnumConstants.ParentTaskStatus.SAVE)) {
				// 返回主任务的ID
				resultJson.put(Constants.MSG, parentTask.getId());
			}

			// 删除主任务下所有的子任务
			childTaskService.delByParentTaskId(parentTask.getId());

			String[] storeCodes = storeCode.split(",");
			Integer childCode = 1;
			for (String store : storeCodes) {
				if (StringUtils.isNotBlank(store)) {
					ChildTask task = new ChildTask();
					task.setParentTaskId(parentTask.getId());
					task.setReward(parentTask.getReward());
					task.setStoreCode(store);
					task.setParentTask(parentTask);
					if (status.equals(EnumConstants.ParentTaskStatus.SAVE)) {
						task.setStatus(EnumConstants.ChildTaskStatus.SAVE);
					} else {
						task.setStatus(EnumConstants.ChildTaskStatus.PUBLISH);
					}
					task.setTaskName(parentTask.getTaskName());
					task.setChildTaskCode(childCode.toString());
					childTaskService.save(task);
					childCode++;
				}
			}
			resultJson.put(Constants.RESULT, Constants.RESULT_SUCCESS);
		} catch (Exception e) {
			LOGGER.error("saveParentTask error {}", e);
			resultJson.put(Constants.RESULT, Constants.RESULT_FAIL);
			resultJson.put(Constants.MSG, "修改任务失败，系统错误");
		}
		return resultJson;
	}

	/**
	 * <发布主任务>
	 *
	 * @param parentTask
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value = "/publish.json")
	@ResponseBody
	public JSONObject publish(@RequestParam(value = "id") Long id) {
		JSONObject resultJson = new JSONObject();
		resultJson.put(Constants.RESULT, Constants.RESULT_FAIL);
		try {
			ParentTask pt = parentTaskService.findById(id);
			pt.setStatus(ParentTaskStatus.PUBLISH);
			parentTaskService.save(pt);
			Map<String, Object> searchParams = new HashMap<String, Object>();
			searchParams.put("EQ_parentTaskId", id);
			List<ChildTask> ctList = childTaskService.findByCondition(searchParams);
			for (ChildTask task : ctList) {
				childTaskService.updateStatus(EnumConstants.ChildTaskStatus.PUBLISH, task.getId());
			}
			resultJson.put(Constants.RESULT, Constants.RESULT_SUCCESS);
		} catch (Exception e) {
			LOGGER.error("publish error {}", e);
			resultJson.put(Constants.RESULT, Constants.RESULT_FAIL);
			resultJson.put(Constants.MSG, "修改任务失败，系统错误");
		}
		return resultJson;
	}

	/**
	 * <编辑主任务/查询主任务详情>
	 *
	 * @param id
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@ResponseBody
	@RequestMapping(value = "/findParentTaskById.json")
	public String getById(@RequestParam(value = "id", defaultValue = "") Long id) {
		try {
			if (id != null) {
				ParentTask pt = parentTaskService.findById(id);
				return JsonUtils.toJson(pt);
			}
		} catch (Exception e) {
			LOGGER.error("find parentTask by id error : {}", e);
		}
		return null;
	}

	/**
	 * <删除主任务>
	 *
	 * @param id
	 * @param response
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value = "/deleteParentTask.json")
	public void deleteById(@RequestParam(value = "id", defaultValue = "") Long id, HttpServletResponse response) {
		try {
			if (id != null) {
				parentTaskService.delete(id);
			}
			RenderUtil.renderText(Constants.SUCCESS, response);
		} catch (Exception e) {
			LOGGER.error("delete parentTask error : {}", e);
			RenderUtil.renderText(Constants.FAIL, response);
		}
	}

	@ResponseBody
	@RequestMapping(value = "/taskImageUpload.json", method = RequestMethod.POST)
	public JSONObject productImageUpload(MultipartHttpServletRequest request) {
		JSONObject resultJson = new JSONObject();
		StringBuffer sb = new StringBuffer();
		try {
			List<String> imageUrlList = Lists.newArrayList();
			Iterator<String> itr = request.getFileNames();
			while (itr.hasNext()) {
				String uploadedFile = itr.next();
				List<MultipartFile> files = request.getFiles(uploadedFile);
				for (MultipartFile file1 : files) {
					String filename = file1.getOriginalFilename();
					String fileName = StringUtils.substring(filename, 0, filename.lastIndexOf("."));
					String fileUrl = FileUtils.fileUpload(file1, Constants.IMAGE_DIR, fileName, request);
					if (StringUtils.isNotBlank(fileUrl)) {
						LOGGER.info(fileUrl);
						imageUrlList.add((File.separator + fileUrl).replace(File.separator, "/"));
					}
				}
			}
			if (!CollectionUtils.isEmpty(imageUrlList)) {
				for (String imageUrl : imageUrlList) {
					sb.append(imageUrl).append(",");
				}
			}
			resultJson.put(Constants.RESULT, Constants.RESULT_SUCCESS);
			resultJson.put(Constants.MSG, sb.substring(0, sb.length() - 1));
		} catch (Exception e) {
			LOGGER.error("upload image files error {}", e);
		}
		return resultJson;
	}

	@ResponseBody
	@RequestMapping(value = "/taskExcelUpload.json", method = RequestMethod.POST)
	public JSONObject taskExcelUpload(MultipartHttpServletRequest request) {
		JSONObject resultJson = new JSONObject();
		try {
			resultJson.put(Constants.RESULT, Constants.RESULT_FAIL);
			LOGGER.debug("upload() start");
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

			String serverUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath() + "/excel/";
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			String ctxPath = request.getSession().getServletContext().getRealPath(File.separator) + "excel"
					+ File.separator;
			LOGGER.info("upload() ctxPath = " + ctxPath);

			// 创建文件夹
			File file = new File(ctxPath);
			if (!file.exists()) {
				if (file.mkdirs()) {
					LOGGER.debug("upload() 创建文件夹成功 ");
				} else {
					LOGGER.debug("upload() 创建文件夹失败 ");
				}
			}
			String fileName = null;
			List<String> codeList = new ArrayList<String>();
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				// 上传文件
				MultipartFile mf = entity.getValue();
				fileName = mf.getOriginalFilename();
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

				File uploadFile = new File(ctxPath + newFileName);

				FileCopyUtils.copy(mf.getBytes(), uploadFile);
				// 对读取Excel表格内容测试
				Map<Integer, String> map = ExcelReader.readExcel(ctxPath + newFileName);
				for (int i = 1; i <= map.size(); i++) {
					codeList.add(map.get(i).split(",")[0]);
				}
				serverUrl += newFileName;

			}
			List<Store> storeList = storeService.findByCode(codeList);
			Map<String, Integer> map = new HashMap<String, Integer>();
			for (String item : codeList) {
				if (map.containsKey(item)) {
					map.put(item, map.get(item).intValue() + 1);
				} else {
					map.put(item, new Integer(1));
				}
			}
			StringBuffer repeatMsg = new StringBuffer();
			Iterator<String> keys = map.keySet().iterator();

			while (keys.hasNext()) {
				String key = keys.next();
				if (map.get(key).intValue() > 1) {
					repeatMsg.append(key + "：" + map.get(key).intValue() + "，");
				}
			}

			// 取出不存在的门店编号
			StringBuffer sb = new StringBuffer();
			List<String> currentList = new ArrayList<String>();
			for (Store s : storeList) {
				currentList.add(s.getStoreCode());
			}
			codeList.removeAll(currentList);
			for (String code : codeList) {
				sb.append(code).append("，");
			}
			String msg = "";
			if (sb.length() > 0) {
				msg = "门店编号:【" + sb.substring(0, sb.length() - 1) + "】在系统中不存在！";
			}
			if (repeatMsg.length() > 0) {
				msg = msg + "<br>" + "门店编号:【" + repeatMsg.substring(0, repeatMsg.length() - 1) + "】添加时重复！";
			}
			resultJson.put(Constants.RESULT, Constants.RESULT_SUCCESS);
			resultJson.put(Constants.ROWS, JsonUtils.toJson(storeList));
			resultJson.put(Constants.MSG, msg);
		} catch (Exception e) {
			LOGGER.error("import excel error {}", e);
		}
		return resultJson;
	}

	private void getChildInfo(ParentTaskBean pt,Long id) {
		// 查询主任务下所有子任务
		List<ChildTask> childTaskList = new ArrayList<ChildTask>();
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("EQ_parentTaskId", id);
		childTaskList = childTaskService.findByCondition(searchParams);

		long childTaskNum = 0;
		// 获取子任务的个数

		childTaskNum = childTaskList.size();

		// 已完成的数量[已提交+审核通过+审核未通过]
		Integer finishTaskNum = 0;
		// 审核通过数量
		Integer checkPassNum = 0;
		// 审核未通过数量
		Integer checkNoPassNum = 0;
		// 已接单数目
		Integer pickUpNum = 0;

		for (ChildTask child : childTaskList) {
			if (null != child.getUserId()) {
				pickUpNum++;
			}
			switch (child.getStatus()) {
			case SAVE:
				break;
			case PUBLISH:
				break;
			case DOING:
				break;
			case SUBMIT:
				finishTaskNum++;
				break;
			case PASS:
				checkPassNum++;
				break;
			case NOPASS:
				checkNoPassNum++;
				break;
			case CLOSE:
				break;
			default:
				break;
			}
		}
		// 已接单
		pt.setPickup(pickUpNum.toString());
		// 子任务数量
		pt.setAll(Long.valueOf(childTaskNum).toString());
		// 已完成的子任务数量
		pt.setSubmit(finishTaskNum.toString());
		// 审核通过的数量
		pt.setCheck(checkPassNum.toString());
		// 审核未通过的数量
		pt.setCheckfail(checkNoPassNum.toString());
	}

}